// components/tabs/tabs.js
import { throttle } from "../../utils/utils";
Component({
  options: {
    multipleSlots: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    tabs: {
      type: Array,
      value: [],
    },
    active: {
      type: Number,
      value: 0,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentTabIndex: 0,
  },
  observers: {
    active: function (active) {
      this.setData({
        currentTabIndex: active,
      });
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    handleTabChange: throttle(function (event) {
      const index = event.currentTarget.dataset.index;
      if (index === this.data.currentTabIndex) {
        return;
      }
      this.setData({
        currentTabIndex: index,
      });
      this.triggerEvent("change", { index });
    }, 500),
    handleTouchMove(event) {
      const direction = event.direction;
      const currentTabIndex = this.data.currentTabIndex;
      const targetTabIndex = direction + currentTabIndex;
      if (targetTabIndex < 0 || targetTabIndex > this.data.tabs.length - 1) {
        return;
      }
      const customEvent = {
        currentTarget: {
          dataset: {
            index: targetTabIndex,
          },
        },
      };
      this.handleTabChange(customEvent);
    },
  },
});
